// pages/booking/booking.js
Page({
  data: {
    backendUrl: 'http://127.0.0.1:88/api/user/',
    bookingType: 'coach', // coach-私教 course-团课
    dateList: [],
    currentDate: '',
    coachList: [],
    courseList: [],
    selectedCategory: '', // 选中的课程分类
    categories: [], // 课程分类列表
  },

  onLoad() {
    this.initDateList();
    this.loadData();
  },

  // 初始化日期列表
  initDateList() {
    const dateList = [];
    const days = ['日', '一', '二', '三', '四', '五', '六'];
    const today = new Date();
    
    for (let i = 0; i < 7; i++) {
      const date = new Date();
      date.setDate(today.getDate() + i);
      
      let dayText = i === 0 ? '今日' : 
                   i === 1 ? '明日' : 
                   '周' + days[date.getDay()];
      
      dateList.push({
        fullDate: this.formatFullDate(date),
        day: date.getDate(),
        weekday: dayText
      });
    }

    const currentDate = this.formatFullDate(today);
    this.setData({
      dateList,
      currentDate
    });
  },

  // 格式化完整日期 YYYY-MM-DD
  formatFullDate(date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  // 切换预约类型
  switchTab(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({ 
      bookingType: type,
      courseList: [], // 清空课程列表
    });
    this.loadData();
  },

  // 选择日期
  selectDate(e) {
    const date = e.currentTarget.dataset.date;
    this.setData({ currentDate: date });
    this.loadData();
  },

  // 加载数据
  loadData() {
    if (this.data.bookingType === 'coach') {
      this.loadCoachList();
    } else {
      this.loadCourseList();
    }
  },

  // 加载教练列表
  loadCoachList() {
    wx.request({
      url: this.data.backendUrl + 'get_coach_list.php',
      data: {
        date: this.data.currentDate
      },
      success: (res) => {
        if (res.data.status === 'success') {
          this.setData({
            coachList: res.data.list
          });
        }
      }
    });
  },

  // 加载团课列表
  loadCourseList() {
    wx.showLoading({
      title: '加载中...'
    });
    
    wx.request({
      url: this.data.backendUrl + 'get_course_list.php',
      data: {
        date: this.data.currentDate
      },
      success: (res) => {
        if (res.data.status === 'success') {
          // 处理时间格式
          const courseList = res.data.list.map(course => {
            // 格式化时间显示
            const startTime = course.start_time.substring(0, 5);
            const endTime = course.end_time.substring(0, 5);

            // 使用 iOS 兼容的日期格式
            const courseDate = course.course_date.replace(/-/g, '/');
            const courseDateTime = new Date(`${courseDate} ${startTime}:00`);
            const now = new Date();

            // 计算课程状态
            let status;
            if (course.booked_count >= course.capacity) {
              status = {
                code: 'full',
                text: '已满'
              };
            } else if (courseDateTime <= now) {
              status = {
                code: 'started',
                text: '已开始'
              };
            } else {
              status = {
                code: 'available',
                text: '可预约'
              };
            }

            return {
              ...course,
              start_time: startTime,
              end_time: endTime,
              status
            };
          });

          this.setData({ courseList });
        } else {
          wx.showToast({
            title: res.data.message || '加载失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },


  // 跳转到教练详情
  goToCoachDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/coach-detail/coach-detail?id=${id}`
    });
  },

  // 跳转到预约页面
  goToBooking(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/booking-coach/booking-coach?id=${id}&date=${this.data.currentDate}`
    });
  },

  // 跳转到课程详情
  goToCourseDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/course-detail/course-detail?id=${id}`
    });
  }
})